<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue中的路由</title>
    <!-- 引用vue.js库 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue-router/dist/vue-router.js"></script>
</head>
<body>
  
    <div id="app">
        <p>
            <!-- 使用 router-link 组件来导航. to属性指定导航地址-->
            <!-- router-link相当于<a>标签 to相当于href -->
            <router-link to="/home">home</router-link>
            <router-link to="/news">news</router-link>
        </p>
        <!-- 路由出口（路由匹配到的组件将渲染在这里） -->
        <router-view></router-view>
    </div>


    <template id="home">
        <div>
            <h2>首页</h2>
            <router-link to="/home/login">登录</router-link>
            <router-link to="/home/reg">注册</router-link>
            <router-view></router-view>
        </div>
    </template>

    <template id="login">
        <div>
            登录的界面
        </div>
    </template>

    <template id="reg">
        <div>
            注册的界面
        </div>
    </template>

    <template id="news">
        <div>
            新闻
        </div>
    </template>
    
    <script>
        //1. 定义路由的组件
        const Home = {template:'#home'}
        const News = {template:'#news'}
        const Login = {template:'#login'}
        const Reg = {template:'#reg'}

        // 2. 定义路由规则对象（每个路由应该映射一个组件）
        const routes = [
        {
            path:'/',
            redirect:'/home'
        },
        {
            path: '/home',  //对应   <router-link to="/home">home</router-link>
            component: Home,  //对应   const Home = {template:'#home'}
            // 配制子路由
            children:[
                {
                    path:'/home/login',
                    component:Login
                },
                {
                    path:'/home/reg',
                    component:Reg
                }
            ]

        },{
            path: '/news',
            component: News
        }
    ]

        // 3. 创建 router 实例，然后传 `routes` 配置
        const router = new VueRouter({
            //如果路由规则对象名也为routes，那么就可以简写为 routes
            routes  
        })


        // 4. 将路由对象挂载到Vue实例上
        // 通过 router 配置参数注入路由，从而让整个应用都有路由功能
        var vm = new Vue({
            el: '#app',
            data: {},
            // 将路由添加到Vue中
            router
        })

    </script>
 
</body>
</html>